<?php
/**
 * 增加电子相册相关信息
 * User: Huashun
 * Date: 2018/8/16
 * Time: 11:41
 */

namespace common\helpers;


use yii\db\Connection;

class Album
{
    public static $sql = '192.168.1.131';
    public static $ftp = '192.168.1.131';

    public static function addAccount($username,$password)
    {
        if(!self::sqlGetPwd($username))
        {
            self::sqlAddUser($username,$password);
            self::ftpAddDir($username);
        }
    }
    public static function ftpAddDir($path,$ftpName='admin',$ftpPasswd='admin')
    {
        $ftp = ftp_connect(self::$ftp, 21, 90);
        ftp_login($ftp,$ftpName,$ftpPasswd);
        ftp_mkdir($ftp,$path);
    }

    public static function sqlAddUser($username,$password)
    {
        $db = new Connection([
            'dsn' => 'mysql:host='.self::$sql.';dbname=proftpd',
            'username' => 'admin',
            'password' => '@Guomao2726',
            'charset' => 'utf8',
        ]);

        $db->createCommand()->insert('ftpusers',[
            'userid' => $username,
            'passwd' => $password,
            'homedir' => '/sostudy/upload/'.$username
        ])->execute();
    }

    public static function sqlEditUser($username,$password)
    {
        $db = new Connection([
            'dsn' => 'mysql:host='.self::$sql.';dbname=proftpd',
            'username' => 'admin',
            'password' => '@Guomao2726',
            'charset' => 'utf8',
        ]);

        $db->createCommand()->update('ftpusers',['passwd' => $password],['userid' => $username])->execute();
    }

    public static function sqlGetPwd($username)
    {
        $db = new Connection([
            'dsn' => 'mysql:host='.self::$sql.';dbname=proftpd',
            'username' => 'admin',
            'password' => '@Guomao2726',
            'charset' => 'utf8',
        ]);

        return $db->createCommand('select passwd from ftpusers where userid =:NAME')->bindValues([':NAME'=>$username])->queryOne();
    }
}